<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Articel;
use App\Http\Model\Category;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class ArticleController extends CommonController
{
    //get 方法 admin/article 路由
    public function index()
    {
        //调用分页方法
        $data=Articel::orderBy('art_id','desc')->paginate(5);

        return view('admin.article.index',compact('data'));
    }

    //get 方法 admin/article/create 路由
    public function create()
    {

        $cate = new Category;
        $data = $cate->tree();
        return view('admin.article.add', compact('data'));
    }

    //添加分类提交方法admin/article/
    public function store()
    {
        $input = Input::except('_token');
        $input['art_time'] = time();

        $rules = array(

            'art_title' => 'required ',
            'art_content' => 'required ',
        );
        $mes = array(

            'art_title.required' => '文章标题不能为空!',
            'art_content.required' => '文章内容不能为空!',
        );

        $validator = Validator::make($input, $rules, $mes);

        if ($validator->passes()) {
                $res = Articel::create($input);
                if ($res) {
                    return redirect('admin/article');
                } else {
                    return back()->with('errors', '数据填充失败，请稍后重试');
                }

        }else {
            return back()->withErrors($validator);
        }

    }
    //get 方法  admin/article/{article}/edit 路由 编辑文章
    public function edit($art_id)
    {    //取得分类名称
        $cate=new Category;
        $data=$cate->tree();
        $filed=Articel::find($art_id);

        return  view('admin.article.edit',compact('data','filed'));
    }

    //PUT 方法 admin/article/{article} 路由
    public function update($art_id)
    {
        $input=Input::except('_token','_method');
        $res=Articel::where('art_id',$art_id)->update($input);

        if($res){
            return redirect('admin/article');
        }else{
            return back()->with('errors','文章数据更新失败，请稍后重试！');
        }

    }

    //delete.admin/article/{article}   删除单个文章
    public function destroy($art_id)
    {
        $re = Articel::where('art_id',$art_id)->delete();
        if($re){
            $data = [
                'status' => 0,
                'msg' => '文章删除成功！',
            ];
        }else{
            $data = [
                'status' => 1,
                'msg' => '文章删除失败，请稍后重试！',
            ];
        }
        return $data;
    }
}
